package com.lanou.userLogin.order.web.servlet;

import com.lanou.userLogin.cart.domin.CartBook;
import com.lanou.userLogin.cart.domin.CartItem;
import com.lanou.userLogin.order.domain.Order;
import com.lanou.userLogin.order.domain.OrderBook;
import com.lanou.userLogin.order.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/orderServlet")
public class OrderServlet extends HttpServlet {

    private OrderService os = new OrderService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();

        //获取总价钱
        double countPrice = (double) session.getAttribute("sumMoney");

        //获取登录人的uid
        String uid = (String) session.getAttribute("uid");

        //oid:随机数
        Random random = new Random();
        int ran = random.nextInt(10000);
        String oid = String.valueOf(ran);

        //格式化当前时间
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String time = df.format(date);

        //地址
        String address = "1111111111";

        //将订单初始状态设为1
        String state = "1";

        //添加订单
        os.insertOrder(oid, time, countPrice, state, uid, address);

        List<CartBook> cartList = (List<CartBook>) session.getAttribute("cartList");

        //遍历
        for (CartBook cartBook : cartList) {
            String iid = String.valueOf(random.nextInt(10000));
            String total = String.valueOf(cartBook.getTotalPrice());
            //根据bid添加订单项
            os.insertOrderItem(iid, cartBook.getCount(), total, oid, cartBook.getBid());
        }

        //oid查询当前订单
        Order order = os.selectOrderByoid(oid);

        //oid查询Orderbook的list
        List<OrderBook> orderBook = os.selectOrderBook(oid);

        req.setAttribute("order", order);
        req.setAttribute("orderbook", orderBook);

        //清空购物车
        List<CartBook> cart = new ArrayList<>();
        session.setAttribute("cartList", cart);

        req.getRequestDispatcher("/jsps/order/desc.jsp").forward(req, resp);
    }
}

